package com.leyou.mongodemo.Test;

import com.leyou.mongodemo.pojo.User;
import com.leyou.mongodemo.repository.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongoDemoApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void testSave() {
        User user = new User(1L, "Amy", 16);
        userRepository.save(user);
    }

    @Test
    public void saveAll() {
        List<User> list = new ArrayList<>();
        list.add(new User(1L, "Amy", 16));
        list.add(new User(2L, "Lucy", 21));
        list.add(new User(3L, "Jack", 20));
        list.add(new User(4L, "Tom", 25));
        list.add(new User(5L, "John", 18));

        userRepository.saveAll(list);
    }

    @Test
    public void testUpdate(){
        // id存在，则修改
        User user = new User(1L, "Amy", 15);

        userRepository.save(user);
    }

    //Optional  JDK8返回结果，永远不可能返回null
    @Test
    public void testFindById(){
        Optional<User> result = userRepository.findById(1L);

        result.ifPresent(System.out::println);
    }

    @Test
    public void testFindAll(){
        List<User> list = userRepository.findAll();
        list.forEach(System.out::println);
    }

    @Test
    public void testFindByPage(){
        // 查询，PageRequest就是分页条件对象，
        Page<User> info = userRepository.findAll(PageRequest.of(0, 3, Sort.Direction.DESC, "age"));
        // 总页数
        int totalPages = info.getTotalPages();
        System.out.println("totalPages = " + totalPages);
        // 总条数
        long totalElements = info.getTotalElements();
        System.out.println("totalElements = " + totalElements);
        // 当前页结果集合
        List<User> list = info.getContent();
        list.forEach(System.out::println);
    }



    @Autowired
    private MongoTemplate mongoTemplate;

    //复杂操作：更新单个字段，效率更高  需要使用mongoTemplate
    @Test
    public void testUpdate2(){
        mongoTemplate.update(User.class)
                // 匹配条件
                .matching(Query.query(Criteria.where("age").gte(20)))
                // 更新条件 inc:包括
                .apply(new Update().inc("age", 100))
                // 更新几个？
                .all();//.first()更新一个
    }
}
